package com.miplus.ccrm.uploadjob.service;

import com.miplus.ccrm.common.JPubUtils;
import com.miplus.ccrm.common.R;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.util.Objects;

import static jdk.nashorn.internal.ir.debug.ObjectSizeCalculator.getObjectSize;
@Aspect
@Component
@Slf4j
public class RequestLoggingAspect {
    @Pointcut("execution(* com.miplus.ccrm.uploadjob.controller.*.*(..))")
    public void loggableMethods(){

    }

    @Before("loggableMethods()")
    public void logReguest(JoinPoint joinPoint) {
        HttpServletRequest h=((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        log.info("{} {}.Recv:{}",
                JPubUtils.getReqIpAddr(h),
                joinPoint.getSignature().getName(),
                joinPoint.getArgs()
        );
        h.setAttribute("request_ts",String.valueOf(System.currentTimeMillis()));
    }

    @AfterReturning(pointcut = "loggableMethods()",returning = "result")
    public void logResponse(JoinPoint joinPoint, Object result){
        HttpServletRequest h=((ServletRequestAttributes) Objects.requireNonNull(RequestContextHolder.getRequestAttributes())).getRequest();
        String ln = (String) h.getAttribute("request_ts");
        try{
            log.info("{} {}.Resp:status={},size={},timeron={} {}",
                    JPubUtils.getReqIpAddr(h),
                    joinPoint.getSignature().getName(),
                    ((R) result).getCode(),
                    getObjectSize(result),
                    JPubUtils.getTimeSpan(ln),
                    result
            );
        }
        catch (HttpMessageNotWritableException e){//返回非R结果文件类型，比如录音文件流等
            log.info("{} {}.Resp:status={},timeron={}",
                    JPubUtils.getReqIpAddr(h),
                    joinPoint.getSignature().getName(),
                    e.getMessage(),
                    JPubUtils.getTimeSpan(ln)
            );
        }
    }
}
